package com.dxj1992.intercepter;

import com.dxj1992.entity.AdminUsers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

public class AdminInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI();
        AdminUsers admin = (AdminUsers) session.getAttribute("admin");
        if (requestURI.equals("/admin/login")) {
            if (!Objects.isNull(admin)) {
                response.sendRedirect("/admin/index");
                return false;
            }
            return true;
        }

        if (Objects.isNull(admin)) {
            response.sendRedirect("/admin/login");
            return false;
        }
        return true;
    }

}
